#!/bin/bash

BASE_PATH=$ZBP_BASE_PATH

if [[ -z "$ZBP_BASE_PATH" ]]; then
    echo "/etc/profile 中未配置 ZBP_BASE_PATH 变量"
    BASE_PATH="/data"
fi

echo "当前使用部署根路径为 $BASE_PATH"

PROJECT_NAME=zbp-lrnr-web
PROJECT_DIR=$BASE_PATH/zbp/software/nginx_1.23.2/html/
FILES=("settings.js" "logo.png" "pro.ico" "logoZy.png")

if [ -d "$PROJECT_DIR/$PROJECT_NAME" ]; then
    echo "当前有在使用的项目文件夹,进行备份操作"
    cp -r $PROJECT_DIR/$PROJECT_NAME ./
    tar -zcvf $PROJECT_NAME.$(date "+%Y%m%d%H%M").tar.gz $PROJECT_NAME
    mv ./*.tar.gz bak/
    rm -rf $PROJECT_NAME
  else
    echo "当前无在使用的项目文件夹,跳过备份"
fi

echo "解压项目zip"

if [ ! -e "$PROJECT_NAME.zip" ]; then
    echo "$PROJECT_NAME.zip不存在"
	exit
fi

command -v unzip

if [ $? == 1 ]; then
	yum -y install unzip
fi

unzip $PROJECT_NAME.zip


echo "删除当前在使用的项目文件夹"
if [ -d "$PROJECT_DIR/$PROJECT_NAME" ]; then
    rm -rf $PROJECT_DIR/$PROJECT_NAME
fi

echo "部署项目到nginx的html"
if [ -d "$PROJECT_NAME" ]; then
    mv $PROJECT_NAME $PROJECT_DIR/
  else
    if [ -d "dist" ]; then
        echo "解压后为dist文件夹"
        mv dist $PROJECT_DIR/$PROJECT_NAME
      else
        echo "解压后的文件夹名称错误,安装失败"
        exit
    fi
fi
 
for file in "${FILES[@]}"; do
    if [ ! -e "$file" ]; then
		echo "缺少$file文件"   
	else
		rm -rf $PROJECT_DIR/$PROJECT_NAME/$file
		cp $file $PROJECT_DIR/$PROJECT_NAME/
    fi
done

echo "清理多余备份文件"
cd bak
number=7
success=0
while (success=0)
do
delfile=`ls -l -crt $PROJECT_NAME.* | awk '{print $9 }' | head -1`
count=`ls -l -crt $PROJECT_NAME.* | awk '{print $9 }' | wc -l`
if [ $count -gt $number ]; then
   rm $delfile
   echo "删除最早生成的备份文件: $delfile"
else
   success=1
   break;
fi
done

echo "安装完成"
